package com.example.adabank3.controller;

import com.example.adabank3.entity.Users;
import com.example.adabank3.entity.UsersExample;
import com.example.adabank3.util.Result;

import org.springframework.web.bind.annotation.*;
import com.example.adabank3.mapper.UsersMapper;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    final UsersMapper usersMapper;

    public UserController(UsersMapper usersMapper) {
        this.usersMapper = usersMapper;
    }


    @PostMapping("/login")
    public Result<Users> login(@RequestBody Map<String, String> data, HttpSession session) {
        String username = data.get("username");
        String password = data.get("password");
        Result result = new Result<Users>();



        try {

            UsersExample usersExample = new UsersExample();
            UsersExample.Criteria criteria = usersExample.createCriteria();
            criteria.andUsernameEqualTo(username);
//            criteria.andPasswordEqualTo(password);
            List<Users> list = usersMapper.selectByExample(usersExample);

            //查到了对应用户信息。登录成功
            if (list != null && list.size() > 0) {
                result.setStatus("OK");
                result.setMessage("登录成功");
                session.setAttribute("username",username);
            } else {
                result.setStatus("ERROR");
                result.setMessage("用户名密码错误");
            }
//        }catch (UnknownAccountException e){
//            System.out.println("用户名不存在");
//            result.setStatus("ERRO");
//            result.setMessage("用户名不存在，请检查用户名");
//            return  result;
//        }catch (AuthenticationException e) {
//            System.out.println("认证失败");
//            result.setStatus("ERRO");
//            result.setMessage("认证失败，请检查用户名");
//            return  result;
        }catch (Exception e){
            e.printStackTrace();
            result.setStatus("未知错误");
            result.setMessage("无法登录，请检查网络");
            return  result;
        }

        return  result;

    }

    /**
     * 检测是否为登录状态
     * @return OK
     */
    @GetMapping("/me")
    public Result<Users> me(HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username != null) {
            return new Result("OK","YES-LOGIN",username);
        }else {
            return new Result("EOOR","NO-LOGIN",null);
        }

    }
    @PostMapping("/logout")
    public Result<Users> logout(HttpSession session) {
        session.removeAttribute("username");
        return new Result<>("OK",null,null);
    }

}
